package com.zhihuichongcheng.application.ui.im.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupManager;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.exceptions.HyphenateException;
import com.smartlib.cmnObject.recycleView.OnItemOnclick;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.DepInfo;
import com.zhihuichongcheng.application.bean.mine.GroupContactBean;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.im.Constant;
import com.zhihuichongcheng.application.ui.im.adapter.AddMemberAdapter;
import com.zhihuichongcheng.application.ui.im.adapter.ContactAllAdapter;
import com.zhihuichongcheng.application.ui.im.adapter.GroupSelectAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 3water on 2016/11/7.
 */

public class AddMemberToGroupActivity extends BaseActivity implements View.OnClickListener{
    protected List<EaseUser> contactList = new ArrayList<>();
    protected ImageButton clearSearch;
    private RecyclerView mRcvSelectGroup, mRcvSearch;
    private LinearLayout mRlContact;
    private String[] allMembers;
    private ExpandableListView mElvContact;
    private GroupSelectAdapter mAdapter = null;
    private List<UserBean> mSelectData = new ArrayList<>();
    private EditText query = null;
    private UserBean mUser;
    private String groupName = "";
    private ContactAllAdapter mContactAllAdapter;
    private List<UserBean> mFriends = new ArrayList<>();
    private AddMemberAdapter adapter;
    private TextView mTvPleaseChoose;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private String mGroupId;
    private List<String> mListMember = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group);
        initView();
        initData();
    }


    private void loadGroupMember()
    {
        Intent intent = getIntent();
        if(intent!=null)
        {
            mGroupId = intent.getStringExtra("groupId");
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final EMGroup group = EMClient.getInstance().groupManager().getGroupFromServer(mGroupId);

                    mListMember = group.getMembers();

                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            loadData(mFriends);
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void initView() {
        mTvPleaseChoose = (TextView)findViewById(R.id.tv_please_choose);
        mRcvSearch = (RecyclerView) findViewById(R.id.rcv_search);
        mRcvSearch.setLayoutManager(new LinearLayoutManager(mContext));
        mContactAllAdapter = new ContactAllAdapter(mContext);
        mRcvSearch.setAdapter(mContactAllAdapter);
        mRlContact = (LinearLayout) findViewById(R.id.rl_contact);
        setTitle("添加群成员");
        mElvContact = (ExpandableListView) findViewById(R.id.elv_contact);
        mRcvSelectGroup = (RecyclerView) findViewById(R.id.rcv_select_group);
        mAdapter = new GroupSelectAdapter(mContext);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRcvSelectGroup.setLayoutManager(manager);
        mRcvSelectGroup.setAdapter(mAdapter);
        query = (EditText) findViewById(com.hyphenate.easeui.R.id.query);
        clearSearch = (ImageButton) findViewById(com.hyphenate.easeui.R.id.search_clear);
        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideKeyboard(query);
            }
        });
        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    List<UserBean> list = filter(s.toString());
                    if (list.size() > 0) {
                        mRlContact.setVisibility(View.GONE);
                        mContactAllAdapter.setData(list);
                        mContactAllAdapter.setSelsetData(mSelectData);
                        mContactAllAdapter.notifyDataSetChanged();
                        mRcvSearch.setVisibility(View.VISIBLE);
                    }
                } else {

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mContactAllAdapter.setOnclick(new OnItemOnclick<UserBean>() {
            @Override
            public void onClick(UserBean userBean, int position) {
                mRcvSearch.setVisibility(View.GONE);
                mRlContact.setVisibility(View.VISIBLE);
                if(!mListMember.contains(userBean.getEasemobNumber()))
                {
                    adapter.setSelectUser(userBean);
                    adapter.notifyDataSetChanged();
                    addSelectData(userBean);
                }
                query.setText("");
            }
        });
    }

    private void initData() {
        mUser = app.getUser();
        mFriends = mUser.getFriends();

        loadGroupMember();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.tv_ok:
                String desc = "test";
                String reason = "Invite to join the group";
                reason = EMClient.getInstance().getCurrentUser() + reason + groupName;
                EMGroupManager.EMGroupOptions option = new EMGroupManager.EMGroupOptions();
                option.maxUsers = 200;
                option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin;
                try {
                    final EMGroup emGroup = EMClient.getInstance().groupManager().createGroup(groupName, desc, allMembers, reason, option);
                    Bundle bundle = new Bundle();
                    bundle.putInt(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                    bundle.putString("userId", emGroup.getGroupId());
                    startActivity(ChatActivity.class, bundle);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    /***
     *
     */

    public List<UserBean> filter(String str) {
        List<UserBean> easeUsers = new ArrayList<>();
        for (int i = 0; i < mFriends.size(); i++) {
            UserBean easeUser = mFriends.get(i);
            if (easeUser.getUserName().contains(str)) {
                easeUsers.add(easeUser);
            }
        }

        return easeUsers;
    }

    private void loadData(List<UserBean> list) {
        final List<String> groups = new ArrayList<>();
        List<List<GroupContactBean>> childs = new ArrayList<>();
        List<GroupContactBean> childItem = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            UserBean easeUser = list.get(i);
            final DepInfo info = easeUser.getDept();
            if (info != null) {
                DepInfo preInfo = null;
                if (i > 0) {
                    preInfo = list.get(i - 1).getDept();
                }
                String preHead = "";
                if (preInfo != null) {
                    preHead = preInfo.getDeptName();
                }
                String header = info.getDeptName();
                if (i == 0 || TextUtils.isEmpty(preHead) || header != null && !header.equals(preHead)) {
                    if (!TextUtils.isEmpty(header)) {
                        groups.add(header);
                        if (i > 0) {
                            childs.add(childItem);
                        }
                        childItem = new ArrayList<>();
                    }
                }
                GroupContactBean bean = new GroupContactBean();
                bean.setBean(easeUser);
                bean.setSelect(false);
                childItem.add(bean);
            }
        }
        childs.add(childItem);
        adapter = new AddMemberAdapter(mContext, groups, childs);
        adapter.setShowChildNum(false);
        mElvContact.setAdapter(adapter);
        mElvContact.setGroupIndicator(null);
        mElvContact.expandGroup(0);
        adapter.setMembers(mListMember);
        adapter.setOnItemClick(new OnItemOnclick<UserBean>() {
            @Override
            public void onClick(UserBean userBean, int position) {
                addSelectData(userBean);
            }
        });
    }


    private void addSelectData(UserBean userBean)
    {
        if (!mSelectData.contains(userBean)) {
            mSelectData.add(userBean);
        } else {
            mSelectData.remove(userBean);
        }
        if (mSelectData.size() > 0) {
            mTvPleaseChoose.setVisibility(View.GONE);
            mRcvSelectGroup.setVisibility(View.VISIBLE);
            setTvRight("确定(" + mSelectData.size() + ")", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    allMembers = new String[mSelectData.size()];
                    for (int j = 0; j < mSelectData.size(); j++) {
                        UserBean selectBean = mSelectData.get(j);
                        allMembers[j] = selectBean.getEasemobNumber();
                        if (j == mSelectData.size() - 1) {
                            groupName = groupName + selectBean.getUserName();
                        } else {
                            groupName = groupName + selectBean.getUserName() + ",";
                        }
                    }
                    groupName = groupName + "," + mUser.getUserName() + "(" + (mSelectData.size() + 1) + ")";
                    addGroup(groupName, allMembers);
                }
            });
        } else {
            mRcvSelectGroup.setVisibility(View.GONE);
            mTvPleaseChoose.setVisibility(View.VISIBLE);
            setTvRight("", null);
        }
        mAdapter.setData(mSelectData);
        mAdapter.notifyDataSetChanged();
    }


    private void addGroup(String groupName, final String[] allMembers) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().groupManager().addUsersToGroup(mGroupId, allMembers);
                    Bundle bundle = new Bundle();
                    bundle.putString("userId",mGroupId);
                    startActivity(ChatActivity.class,bundle);
                    finish();
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
